package com.guigu.dh.api.service.impl;

import com.guigu.dh.api.service.ApiDepartmentService;
import com.guigu.dh.common.result.Result;
import com.guigu.dh.pojo.hosp.Department;
import com.guigu.dh.repository.DepartmentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class ApiDepartmentServiceImpl implements ApiDepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;

    // 分页查询的方法
    @Override
    public Result pagingDepartment(Map<String, String> map) {
        // 取出分页条件
        String currentPage = map.get("currentPage");
        String limit = map.get("limit");
        // 分页条件封装
        /*Department department = new Department();
        department.setIsDeleted(0);
        Example<Department> of = Example.of(department);*/
        PageRequest pageable = PageRequest.of(Integer.parseInt(currentPage)-1, Integer.parseInt(limit));
        Page<Department> all = departmentRepository.findAll(/*of,*/pageable);
        return Result.ok(all);
    }

    // 删除科室的方法
    @Override
    public Result doDel(String depcode) {
        Department department = departmentRepository.getDepartmentByDepcode(depcode);
        departmentRepository.deleteById(department.getId());
        return Result.ok();
    }

    // 添加或修改科室的方法
    @Override
    public Result saveDepartment(Department department) {
        // 先根据科室编号查询是否存在
        Department byDepcode = departmentRepository.getDepartmentByDepcode(department.getDepcode());
        if (byDepcode == null) {
            department.setCreateTime(new Date());
        }
        department.setIsDeleted(0);
        department.setUpdateTime(new Date());
        Department save = departmentRepository.save(department);
        if (save != null) {
            return Result.ok(save);
        }
        return Result.fail();
    }


}
